"""
应用入口文件
"""
import os
import click
from flask.cli import with_appcontext
from dotenv import load_dotenv
from app import create_app, db
from app.models import Dataset, AnalysisTask

# 加载环境变量
load_dotenv()

# 创建应用实例
app = create_app(os.getenv('FLASK_ENV', 'development'))

@click.command('init-db')
@with_appcontext
def init_db_command():
    """初始化数据库"""
    try:
        click.echo('正在创建数据库...')
        db.create_all()
        click.echo('数据库创建成功！')
        
        # 检查uploads目录
        if not os.path.exists(app.config['UPLOAD_FOLDER']):
            os.makedirs(app.config['UPLOAD_FOLDER'])
            click.echo(f"创建上传目录: {app.config['UPLOAD_FOLDER']}")
            
        click.echo('初始化完成！')
    except Exception as e:
        click.echo(f'初始化失败: {str(e)}', err=True)
        raise

@click.command('reset-db')
@with_appcontext
def reset_db_command():
    """重置数据库"""
    if click.confirm('此操作将删除所有数据，确定继续吗？'):
        try:
            click.echo('正在删除数据库...')
            db.drop_all()
            click.echo('正在重新创建数据库...')
            db.create_all()
            click.echo('数据库重置成功！')
        except Exception as e:
            click.echo(f'重置失败: {str(e)}', err=True)
            raise

@click.command('list-routes')
@with_appcontext
def list_routes_command():
    """打印所有已注册的Flask路由"""
    import urllib
    output = []
    for rule in app.url_map.iter_rules():
        methods = ','.join(sorted(rule.methods))
        line = urllib.parse.unquote(f"{rule.endpoint:30s} {methods:20s} {rule}")
        output.append(line)
    click.echo("\n已注册的路由:")
    for line in sorted(output):
        click.echo(line)

# 直接注册命令到应用
app.cli.add_command(init_db_command)
app.cli.add_command(reset_db_command)
app.cli.add_command(list_routes_command)

@app.shell_context_processor
def make_shell_context():
    """为Flask shell添加上下文"""
    return {
        'db': db,
        'Dataset': Dataset,
        'AnalysisTask': AnalysisTask
    }

if __name__ == '__main__':
    print("已注册的路由：")
    for rule in app.url_map.iter_rules():
        print(rule)
    app.run(host='0.0.0.0', port=5000)